import { baseUrl, urlParams,uploadUrl,failLogin } from "./index";
import axios from "axios";

function getBaseObj() {
  return { token: urlParams.get("token") };
}

function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    try {
      axios({
        method: "GET",
        url: baseUrl + url,
        params: JSON.parse(JSON.stringify(params)),
        headers: {
          ...getBaseObj()
        }
      }).then(res => {
        failLogin(res)
        resolve(res.data)
      })
        .catch(res => resolve({ code: "", msg: "网络异常！" }));
    } catch (e) {
      resolve({ code: "", msg: "网络异常！" });
    }
  });
}

function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    try {
      axios({
        method: "POST",
        url: baseUrl + url,
        data,
        headers: {
          ...getBaseObj()
        }
      }).then(res => {
        failLogin(res)
        resolve(res.data)
      })
        .catch(res => resolve({ code: "", msg: "网络异常！" }));
    } catch (e) {
      resolve({ code: "", msg: "网络异常！" });
    }
  });
}

function upload(file) {
  const formData = new FormData()
  formData.append('file', file.file)
  return new Promise((resolve, reject) => {
    try {
      axios({
        method: "POST",
        url: uploadUrl,
        data: formData,
        headers: {
          ...getBaseObj(),
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        failLogin(res)
        resolve(res.data)
      })
        .catch(res => resolve({ code: "", msg: "网络异常！" }));
    } catch (e) {
      resolve({ code: "", msg: "网络异常！" });
    }
  });
}

export default { get, post, upload };
